package historique;

import graphEd.GraphEditor;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

import line.LineChooserHistory;
import DataStorage.EssieuDAOHibernate;
import HibernateSQLite.java.model.Essieu;

import com.mxgraph.util.mxResources;

public class Historique extends JFrame {
	private static final long serialVersionUID = 1L;
	private JComboBox tSite;
	private JComboBox tOrgane;
	private JComboBox tDiversite;
	private JComboBox tAnnee;
	private JComboBox tNumLigne;
	private JLabel lSite;
	private JLabel lOrgane;
	private JLabel lDiversite;
	private JLabel lAnnee;
	private JLabel lNumLigne;
	//private LineChooser lineChooser;
	private LineChooserHistory lineChooser;
	private JTable table;
	private String[] commun;
	//private Infos infos = Infos.getInstance();
	@SuppressWarnings("unused")
	private Object[][] data = {{ Boolean.TRUE , "test"},{ Boolean.FALSE , "zzz"}};
	//private List<Object[]> data = Arrays.asList(new Object[]{Boolean.FALSE , "test"},new Object[]{ Boolean.FALSE , "test"});
	//private String columnNames[] = { "Selected", "Num�ro de s�rie" };
	
	//private JTableModel model;
	private JButton load = new JButton(mxResources.get("load"));
	private JButton go = new JButton(mxResources.get("go"));
	private JButton delete = new JButton(mxResources.get("remove"));
	private ArrayList<String> listFlag;
	private ArrayList<Long> listInfoLigneId = new ArrayList<Long>();

	private DefaultTableModel model;	public Historique(){
		setTitle(mxResources.get("history"));
		setIconImage(new ImageIcon(
					GraphEditor.class
							.getResource("/graphEd/images/renault_sans.png"))
					.getImage());
		
		init();
		makeLayout();
		installListeners();
	}
	

	private void init(){
		// Initialisation
		
		commun = new String[] { mxResources.get("selected"),
				mxResources.get("serialNumber"),
				mxResources.get("path"),
				mxResources.get("system"),
				mxResources.get("diversity"),
				mxResources.get("year"),
				mxResources.get("producingDay"),
				mxResources.get("measuringDay"),
				mxResources.get("operator"),
				mxResources.get("nameCriterion"),
				mxResources.get("filePath"),
				mxResources.get("analysisDay")
				};
		
		tSite = new JComboBox();
		tOrgane = new JComboBox();
		tDiversite = new JComboBox();
		tAnnee = new JComboBox();
		tNumLigne = new JComboBox();

		lSite = new JLabel(mxResources.get("site"), JLabel.RIGHT);
		lOrgane = new JLabel(mxResources.get("system"), JLabel.RIGHT);
		lDiversite = new JLabel(mxResources.get("diversity"), JLabel.RIGHT);
		lAnnee = new JLabel(mxResources.get("year"), JLabel.RIGHT);
		lNumLigne = new JLabel(mxResources.get("lineNumber"), JLabel.RIGHT);

		lineChooser = new LineChooserHistory(tOrgane, tDiversite, tSite, tNumLigne,
				tAnnee);
		
		model = new DefaultTableModel();
		//JTableModel model = new JTableModel();
		
		table = new JTable(model);
		//table.setFillsViewportHeight(true);
		
		//model.addColumn("Selected");
		for(String s:commun){
			model.addColumn(s);
		}
		//model.addColumn("autre");
		
		//for(int i=0; i<5; i++)
		//	model.addRow(new Object[]{ Boolean.FALSE , "test", i});
		//table.setDefaultRenderer(Boolean.class, new DefaultTableCellRenderer());
		

		table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(new JCheckBox()));
		table.getColumnModel().getColumn(0).setCellRenderer(new CheckBoxRenderer());

		//table.getColumn(mxResources.get("selected")).setCellEditor(new DefaultCellEditor(new JCheckBox()));
		//table.getColumn(mxResources.get("selected")).setCellRenderer(new CheckBoxRenderer());
		
		
		//add(new Object[]{ Boolean.TRUE , "autre"});
		table.setAutoCreateRowSorter(true);
		
		listFlag = new ArrayList<String>();

	}

	class CheckBoxRenderer extends JCheckBox implements TableCellRenderer {
		private static final long serialVersionUID = 1L;

		public Component getTableCellRendererComponent(JTable table, Object value,
				boolean isSelected, boolean hasFocus, int row, int column) {
			//System.out.println(">"+row+"\t>"+column);
			//if(row>0){
			//setBorderPainted(false);
			setBackground(Color.white);
			
			if (value==Boolean.TRUE){
				setSelected(true);
				setBackground(Color.gray);
			}else{
				setSelected(false);
				setBackground(Color.white);	
			}
			return this;
		}
	}
	
	private void makeLayout(){
		setLayout(new BorderLayout());
		JPanel panel = new JPanel();
		panel.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();

		// Placement des labels et textfields
		c.fill = GridBagConstraints.BOTH;
		c.gridx = 0;
		c.gridy = 0;
		c.insets = new Insets(5, 10, 0, 0);
		c.weightx = 0.5;
		panel.add(lOrgane, c);
		c.gridx = 1;
		panel.add(tOrgane, c);
		c.gridx = 2;
		panel.add(lNumLigne, c);
		c.gridx = 3;
		panel.add(tNumLigne, c);

		c.insets = new Insets(5, 10, 0, 0);
		c.gridx = 0;
		c.gridy = 1;
		panel.add(lDiversite, c);
		c.gridx = 1;
		panel.add(tDiversite, c);
		c.gridx = 2;
		panel.add(lAnnee, c);
		c.gridx = 3;
		panel.add(tAnnee, c);

		c.insets = new Insets(5, 10, 10, 0);
		c.gridx = 0;
		c.gridy = 2;
		panel.add(lSite, c);
		c.gridx = 1;
		panel.add(tSite, c);
		c.gridx = 2;
		//c.gridwidth=2;

		JPanel panelTable = new JPanel();
		panelTable.setLayout(new BoxLayout(panelTable, BoxLayout.Y_AXIS));
		panelTable.add(table.getTableHeader());
		panelTable.add(new JScrollPane(table));
		
		JPanel panelButtons = new JPanel();
		//panelButtons.setLayout(new BorderLayout());
		panelButtons.add(load);
		panelButtons.add(delete);
		panelButtons.add(go);
		
		this.getContentPane().add(panel, BorderLayout.NORTH);
		this.getContentPane().add(panelTable, BorderLayout.CENTER);
		this.getContentPane().add(panelButtons, BorderLayout.SOUTH);
		this.pack();
		this.setLocationRelativeTo(null);
	}

	private void installListeners(){
		load.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent evt) {
				// On efface les donn�es pr�c�dentes
				for (int i=model.getRowCount()-1 ; i>=0 ; --i)
					model.removeRow(i);
					
				EssieuDAOHibernate essieuDAO = new EssieuDAOHibernate();
				List<Essieu> listEssieu = new ArrayList<Essieu>();
				
				if(tOrgane.getSelectedIndex()==tOrgane.getItemCount()-1){
					listEssieu = essieuDAO.getListEssieuFromHistory();
					System.out.println("if");
				}else{
					listEssieu = essieuDAO.getListEssieuFromHistory();
					System.out.println("else");
					/*listEssieu = essieuDAO.getListEssieuHistory(
							(String) tOrgane.getSelectedItem(),
							(String) tDiversite.getSelectedItem(),
							(String) tSite.getSelectedItem(),
							(String) tNumLigne.getSelectedItem(),
							(String) tAnnee.getSelectedItem());
							*/
				}
				listEssieu = essieuDAO.getListEssieuFromHistory();
				System.out.println("hors if");
				System.out.println("listEssieu size:"+listEssieu.size());
				
				for(Essieu e:listEssieu){
					model.addRow(new Object[]{Boolean.FALSE, e.getN_serie(), e.getChemin(), e.getOrgane(), e.getDiversite(), e.getAnnee(), e.getJour_production(), e.getJour_mesure(), e.getName_operateur(), e.getCritere_name(), e.getFilePath(), e.getJour_analyse()});
					listFlag.add(e.getFlag_mesure());
					listInfoLigneId.add(e.getInformationLigne_id());
				}
			}
		});
		
		// Avant, mettre un dialog avec "Etes-vous s�r de vouloir supprimer ces �l�ments ?"
		delete.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent evt) {
				
				for(int i=0; i<table.getRowCount(); i++){
					Boolean selected = (Boolean)table.getValueAt(i, 0);
					if(selected){
						
						System.out.println("DELETE:"+table.getValueAt(i, 1));
						EssieuDAOHibernate essieuDAO = new EssieuDAOHibernate();
						Essieu essieu = essieuDAO.getEssieuFromHistory((String)table.getValueAt(i, 1), (String)table.getValueAt(i, 2), listFlag.get(i), listInfoLigneId.get(i));
						System.out.println("flag:"+listFlag.get(i));
						essieuDAO.deleteEssieuFromHistory(essieu);
						
						/*for(Essieu e:essieuDAO.getListEssieuFromHistory()){
							//if (essieu.getJour_analyse().equals(table.getValueAt(i, commun.length-1)))
								//essieuDAO.deleteEssieuFromHistory(essieu);
							System.out.println("flag_mesure:"+e.getFlag_mesure());
						}*/
						
						model.removeRow(i);
					}
				}
			}
		});
	}
	
	class JTableModel extends AbstractTableModel {
		private static final long serialVersionUID = 1L;

		Object data[][] = {{ Boolean.FALSE , "test"},{ Boolean.FALSE , "test"}};
		//List<List<Object>> data = new ArrayList<List<Object>>();
		//List<List<Object>> data = Arrays.asList(Boolean.FALSE , "test");
		//List<Object[]> data = Arrays.asList(new Object[]{Boolean.FALSE, "test"}, new Object[]{Boolean.FALSE, "test 2"});
		
		String columnNames[] = { "Selected", "Num�ro de s�rie" };

		//public void addRow(Object[] newData){
		//	data.add(newData);
		//}
		
		public void setData(Object[][] data) {
			this.data = data;
		}
		
		public int getColumnCount() {
			return columnNames.length;
		}

		public int getRowCount() {
			return data.length;
		}

		public String getColumnName(int col) {
			return columnNames[col];
		}

		public Object getValueAt(int row, int col) {
			return data[row][col];
		}

		@SuppressWarnings({ "unchecked", "rawtypes" })
		public Class getColumnClass(int c) {
			if (c==0)
				return Boolean.class;
			else
				return getValueAt(0, c).getClass();
		}


		public boolean isCellEditable(int row, int col) {
			return true;
		}

		public void setValueAt(Object value, int row, int col) {
			data[row][col] = value;
			fireTableCellUpdated(row, col);
		}
	}
	
	/*private JTable initTable(String[] header, int rows) {

		// TODO ajouter une constructeur EditorTable(Model)
		JTable table = new JTable(new JTableModel());
		//table.setTableHeader(new JTableHeader());
		//table.getModel().
		
		return table;
	}*/
	
	public static void main(String args[]) {
		Historique historique = new Historique();
		historique.setVisible(true);
	}
}

